//
//  Shopping_cat_TableViewCell.m
//  DA_V
//
//  Created by 中亿世联前台 on 15/4/22.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "Shopping_cat_TableViewCell.h"
#import "InterFace.h"
#import "ProductListModel.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "CarModel.h"
#import "EncryptionData.h"
#import "Alart_ZhiFuView.h"
#import "GMDCircleLoader.h"
@implementation Shopping_cat_TableViewCell
{
    CarModel *_tempModel;
    Alart_ZhiFuView *_zhiFuAlartView;//提交订单时的弹出框
    UIView *_alertBackview;
    UITapGestureRecognizer *_singleTap;
    UITapGestureRecognizer *_singleTap2;
    UIAlertView *_deletealert;
}

-(void)layoutSubviews{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
//        self.addNum.layer.borderColor = [UIColor grayColor].CGColor;
//        self.addNum.layer.borderWidth = 1.0;
        self.shoppNum.layer.borderColor = LineColor.CGColor;
        self.shoppNum.layer.borderWidth = 1.0;
//    self.shoppNum.delegate = self;
//        self.subtractNum.layer.borderColor = [UIColor grayColor].CGColor;
//        self.subtractNum.layer.borderWidth = 1.0;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    [super layoutSubviews];
}

#pragma -mark 提交订单时的弹出输入密码提示框
-(void)careteAlertPassword{
    
    UIWindow *windows = [[[UIApplication sharedApplication] delegate] window];
    
    _alertBackview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _alertBackview.backgroundColor = [UIColor blackColor];
    _alertBackview.alpha = 0.4;
    [windows addSubview:_alertBackview];
//    @property (weak, nonatomic) IBOutlet UIButton *affirmBut;//确定
//    
//    @property (weak, nonatomic) IBOutlet UIButton *cancelBut;//取消
    _zhiFuAlartView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndexedSubscript:12];
    _zhiFuAlartView.frame = CGRectMake(60, SCREEN_HEIGHT/2-90, SCREEN_WIDTH-120, 140);
    _zhiFuAlartView.titleAlart.text = @"请输入商品数目";
    _zhiFuAlartView.titleAlart.font = [UIFont fontWithName:nil size:17];
    _zhiFuAlartView.password.text = [NSString stringWithFormat:@"%@",self.carModel.Number];
    _zhiFuAlartView.password.secureTextEntry = NO;
    _zhiFuAlartView.password.placeholder = @"请输入商品数目";
    _zhiFuAlartView.password.delegate = self;
    [_zhiFuAlartView.affirmBut setTitle:@"确定" forState:UIControlStateNormal];
    [_zhiFuAlartView.cancelBut setTitle:@"取消" forState:UIControlStateNormal];
    [_zhiFuAlartView.affirmBut addTarget:self action:@selector(affirmClick) forControlEvents:UIControlEventTouchUpInside];
    [_zhiFuAlartView.cancelBut addTarget:self action:@selector(cancelButClick) forControlEvents:UIControlEventTouchUpInside];
    [windows addSubview:_zhiFuAlartView];
    
    
    _singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    _singleTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [_alertBackview addGestureRecognizer:_singleTap];
    [_zhiFuAlartView addGestureRecognizer:_singleTap2];
}

-(void)handleSingleTap:(UITapGestureRecognizer *)sender{
    
    if (SCREEN_HEIGHT < 568) {
        
        // beginAnimations表示此后的代码要“参与到”动画中
        
        [UIView beginAnimations:nil context:nil];
        //设置动画时长
        [UIView setAnimationDuration:0.3];
          _zhiFuAlartView.frame = CGRectMake(60, SCREEN_HEIGHT/2-90, SCREEN_WIDTH-120, 140);
        // commitAnimations,将beginAnimation之后的所有动画提交并生成动画
        [UIView commitAnimations];
    }
    [_zhiFuAlartView.password resignFirstResponder];
}
#pragma -mark 点击弹出框的确定交易
- (void)affirmClick{
    if (_zhiFuAlartView.password.text== nil ||[_zhiFuAlartView.password.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"数目不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if (_zhiFuAlartView.password.text.intValue <= 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"数目不能为0" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [_alertBackview removeGestureRecognizer:_singleTap];
    [_zhiFuAlartView removeGestureRecognizer:_singleTap2];
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
    [self updateCatNumber:_zhiFuAlartView.password.text];
    

}

#pragma -mark 点击弹出框的取消交易
- (void)cancelButClick{
    [_alertBackview removeGestureRecognizer:_singleTap];
    [_zhiFuAlartView removeGestureRecognizer:_singleTap2];
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
}
- (void) keyboardWillHide:(NSNotification *)note{
// [self.shopping_cat_TableViewCellDelegate showTableVierFramEnd:self.carModel];
//    if (self.shoppNum.text.length <=0||[self.shoppNum.text isEqualToString:@"0"]){
//    self.shoppNum.text = @"1";
//    }
//      [self updateCatNumber:self.shoppNum.text];
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//    [self.shopping_cat_TableViewCellDelegate showTableVierFram:self.carModel];、
    if (SCREEN_HEIGHT < 568) {
        
        // beginAnimations表示此后的代码要“参与到”动画中
        
        [UIView beginAnimations:nil context:nil];
        //设置动画时长
        [UIView setAnimationDuration:0.3];
        _zhiFuAlartView.frame = CGRectMake(60, 100, SCREEN_WIDTH-120, 140);
        // commitAnimations,将beginAnimation之后的所有动画提交并生成动画
        [UIView commitAnimations];
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
//    [self.shopping_cat_TableViewCellDelegate showTableVierFramEnd:self.carModel];
//    [textField resignFirstResponder];
//    if (self.shoppNum.text.length <=0||[self.shoppNum.text isEqualToString:@"0"]){
//        self.shoppNum.text = @"1";
//    }
//    [self updateCatNumber:textField.text];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([textField isEqual:_zhiFuAlartView.password]) {
        NSMutableString *text = [textField.text mutableCopy];
        [text replaceCharactersInRange:range withString:string];
        return [text length] <= 5;
    }
    return [self validateNumber:string];
 
}
#pragma -makr 设置电话号码输入框只能输入数字
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}
- (void)showMyCar:(id)data{
    
          //商品价格
    if ([data isKindOfClass:[CarModel class]]) {
        CarModel *model = data;
        _tempModel = model;
        self.carModel = model;
        [self.shoppingImage sd_setImageWithURL:[NSURL URLWithString:model.ThumbPath] placeholderImage:nil];
        self.shoppingName.text = model.ProductName;
        self.price.text = [NSString stringWithFormat:@"%d",model.MarketAmount.intValue];
        [self.shoppNum setTitle: [NSString stringWithFormat:@"%@",model.Number] forState:UIControlStateNormal];
    }
    
}

#pragma - mark 点击商品数目触发的事件
- (IBAction)updateName:(id)sender {
    [self careteAlertPassword];

    
}

#pragma -mark 删除商品按钮事件
- (IBAction)deleteCarProductEnd:(UIButton *)sender {
//    sender.userInteractionEnabled = NO;
//    [self.shopping_cat_TableViewCellDelegate  deleteCarProductEnd:self.carModel];
    
//
    _deletealert = [[UIAlertView alloc] initWithTitle:nil message:@"确定要删除商品吗？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [_deletealert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView == _deletealert) {
        if (buttonIndex == 0) {
             [self deleteProductConntiacion];
        }
    }
    
}
#pragma -mark 加商品数量
- (IBAction)addProductNumber:(UIButton *)sender {
//    sender.userInteractionEnabled = NO;
//    int i = self.shoppNum.text.intValue;
//    ++i;
////    self.shoppNum.text = [NSString stringWithFormat:@"%d",i];
//    [self updateCatNumber:[NSString stringWithFormat:@"%d",i]];
  
}

#pragma -mark 减商品数量
- (IBAction)subtractProductNumber:(UIButton *)sender {
//      sender.userInteractionEnabled = NO;
//    int i = self.shoppNum.text.intValue;
//    --i;
//    self.shoppNum.text = [NSString stringWithFormat:@"%d",i];
//    [self updateCatNumber:[NSString stringWithFormat:@"%d",i]];
//    if (i <=1) {
//        i=1;
//        self.shoppNum.text = [NSString stringWithFormat:@"%d",i];
//    }
}

#pragma -mark 修改商品数目网络请求
- (void)updateCatNumber:(NSString *)number{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    
//    NSMutableArray *parameterArray = [[NSMutableArray alloc]init];
    
     NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    
    NSDictionary *parameter = @{@"AgentID":agentId,@"CartID":self.carModel.CartID,@"Number":number};
    
//    [parameterArray addObject:parameter];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    
    
    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
    
//    EncryptionData *enctytion = [[EncryptionData alloc] init];
    
    NSString *str = [self encodeString:jsonString key:PasswordKey];
    
    NSDictionary *paramer = @{@"sign":str};
    __weak Shopping_cat_TableViewCell *cell = self;
    [manager POST:UpdataCartNunberInterface parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
        cell.subtractNum.userInteractionEnabled = YES;
        cell.addNum.userInteractionEnabled = YES;
        NSString *str = responseObject[@"sign"];
        
        
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
        
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
    
            NSDictionary *dataMyDic = dataDic[@"data"];
            
            NSLog(@"添加购物车数目返回结果 ＝＝＝＝ %@",dataDic);
            NSArray *arr = dataMyDic[@"CartInfo"];
            
            NSDictionary *myDic = [arr firstObject];
            cell.carModel.DiscountPriceAmount = [NSString stringWithFormat:@"%@",dataMyDic[@"DiscountPriceAmount"]];
            cell.carModel.MarketPriceAmount = [NSString stringWithFormat:@"%@",dataMyDic[@"MarketPriceAmount"]];
            
            _tempModel.MarketPrice =  [NSString stringWithFormat:@"%@",myDic[@"MarketPrice"]];
            _tempModel.CartID =  [NSString stringWithFormat:@"%@",myDic[@"CartID"]];
             _tempModel.Number =  [NSString stringWithFormat:@"%@",myDic[@"Number"]];
            [self.shopping_cat_TableViewCellDelegate shopping_cat_TableViewCellEnd:cell.carModel];
        } else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"服务器异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        cell.subtractNum.userInteractionEnabled = YES;
        cell.addNum.userInteractionEnabled = YES;
        NSLog(@"========== %@", [error description]);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }];
    

}

#pragma -mark 删除购物车中的某个商品请求
- (void)deleteProductConntiacion{
    NSLog(@"调用删除调用删除掉用删除");
    
    [GMDCircleLoader setOnView:self withTitle:@"删除中···" animated:YES];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",nil];
    
    
    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    
    NSDictionary *parameter = @{@"AgentID":agentId,@"CartID":self.carModel.CartID};
    

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    
    
    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
    

    
    NSString *str = [self encodeString:jsonString key:PasswordKey];
    
    NSDictionary *paramer = @{@"sign":str};
    
    __weak Shopping_cat_TableViewCell *cell = self;
    [manager POST:DeleteCartProduct parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
        cell.userInteractionEnabled = YES;
        [GMDCircleLoader hideFromView:self animated:YES];
        NSString *str = responseObject[@"sign"];
        
        
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
        
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
            
            NSLog(@"删除购物车购物车返回结果 ＝＝＝＝ %@",dataDic);
            NSDictionary *myDic =dataDic[@"data"];

            cell.carModel.DiscountPriceAmount = [NSString stringWithFormat:@"%@",myDic[@"DiscountPriceAmount"]];
            cell.carModel.MarketPriceAmount = [NSString stringWithFormat:@"%@",myDic[@"MarketPriceAmount"]];
            [cell.shopping_cat_TableViewCellDelegate deleteCarProductEnd:cell.carModel];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CarNumberChange"object:nil];
        } else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"服务器异常,删除失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [GMDCircleLoader hideFromView:self animated:YES];
         cell.userInteractionEnabled = YES;
        NSLog(@"========== %@", [error description]);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }];

}
#pragma mark - 加密
-(NSString *)encodeString:(NSString *)data key:(NSString *)key{
    //    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    //
    //    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",data);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [data length]; i++) {
        position = i % keyLength;
        strChar = [data characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
    
    return base64String1;
}
@end
